import { fastSort } from "./fastsort";

/**
 * @deprecated
 * @param nums
 * @returns
 */
function findMidNum(nums: number[]): number {
    if (nums.length < 2) {
        return 0;
    }
    const midPos = Math.floor(nums.length / 2) - 1;
    console.log("midPos: %s, nums[midPos]: %s", midPos, nums[midPos]);
    return nums.length % 2 === 0
        ? (nums[midPos] + nums[midPos + 1]) / 2
        : nums[midPos];
}

/**
 * @deprecated
 * @param nums1
 * @param nums2
 * @returns
 */
function deprecatedFindMedianSortedArrays(
    nums1: number[],
    nums2: number[]
): number {
    // const nums = [...nums1, ...nums2];
    const midNum1 = findMidNum(nums1);
    const midNum2 = findMidNum(nums2);
    const midPos1 =
        nums1.length % 2 === 0
            ? nums1.length / 2 - 1
            : Math.floor(nums1.length / 2);
    const midPos2 =
        nums2.length % 2 === 0
            ? nums2.length / 2 - 1
            : Math.floor(nums2.length / 2);

    const midNums = [];
    const tempLeftNums = [];
    const tempRightNums = [];
    console.log("midNum1: %s, midNum2: %s", midNum1, midNum2);

    if (midNum2 > midNum1) {
        midNums.push(...nums1.slice(midPos1, nums1.length));
        console.log("midNum2 > midNum1 midNums aft push nums1:", midNums);
        midNums.push(...nums2.slice(0, midPos2 + 1));
        console.log("midNum2 > midNum1 midNums aft push nums2:", midNums);
        tempLeftNums.push(...nums1.slice(0, midPos1));
        tempRightNums.push(...nums2.slice(midPos2 + 1, nums2.length));
    } else {
        midNums.push(...nums2.slice(midPos2, nums2.length));
        console.log("midNum2 <= midNum1 midNums aft push nums2:", midNums);
        midNums.push(...nums1.slice(0, midPos1 + 1));
        console.log("midNum2 <= midNum1 midNums aft push nums1:", midNums);
        tempLeftNums.push(...nums2.slice(0, midPos2));
        tempRightNums.push(...nums1.slice(midPos1 + 1, nums1.length));
    }
    console.log(
        "tempLeftNums: %s, midNums: %s, tempRightNums: %s",
        tempLeftNums,
        midNums,
        tempRightNums
    );
    const sortedArr = fastSort(0, midNums.length - 1, midNums);

    const finalArr = [...tempLeftNums, ...sortedArr, ...tempRightNums];
    console.log("finalArr:", finalArr);
    const midPoses =
        finalArr.length % 2 === 0
            ? [finalArr.length / 2 - 1, finalArr.length / 2]
            : [finalArr.length / 2, finalArr.length / 2];
    const midPos = midPoses.map((v: number) => Math.floor(v));
    console.log("midPos:", midPos);
    return (finalArr[midPos[0]] + finalArr[midPos[1]]) / 2;
}
